import React, { useEffect, useState } from 'react';

const isPhone = !!window.navigator.userAgent.match(/ios|iphone|android|ipad/i);
function useTap(fn, listenPress) {
    const [time, setTime] = useState(0);
    useEffect(
        () => () => {
            clearInterval(time);
        },
        [time]
    );

    if (isPhone) {
        if (listenPress) {
            return {
                onTouchStart: () => {
                    clearInterval(time);
                    const newTime = setInterval(fn, 140);
                    setTime(newTime);
                },
                onTouchEnd: () => {
                    clearInterval(time);
                    fn();
                },
            };
        }

        return {
            onTouchEnd: fn,
        };
    }
    return {
        onClick: fn,
    };
}

export default function ClickItem(props) {
    const {
        onClick, children, listenPress, ...otherProps
    } = props;
    const fn = event => {
        if (event) {
            event.stopPropagation();
            event.preventDefault();
        }
        onClick && onClick();
    };

    // 如果是移动端使用onTouchEnd，反则使用click
    return (
        <li {...useTap(fn, listenPress)} {...otherProps}>
            {children}
        </li>
    );
}
